<template>
  <div class="crud">
    <el-table
      :ref="gridRef"
      v-loading="listLoading"
      :data="showGridData"
      size="mini"
      style="width: 100%"
    >
      <el-table-column
        v-for="(item,index) in gridConfig"
        :key="index"
        :prop="item.prop"
        :class-name="item.className || ''"
        :label="item.label || ''"
        :resizable="!!item.resizable"
        :sortable="item.sortable"
        :align="item.align"
        :type="item.type"
        :show-overflow-tooltip="item.showOverflowTooltip"
        :width="item.width?item.width:''"
        :min-width="item.minWidth?item.minWidth:''"
        :fixed="item.fixed"
      >
        <template slot-scope="scope">
          <cell
            v-if="item.render"
            :row="scope.row"
            :column="item"
            :index="scope.$index"
            :render="item.render"
          />
          <template v-else-if="item.filter">{{ item.filter(scope.row[item.prop]) }}</template>
          <formatter-component
            v-else
            :format="item.format"
            :options="item.options"
            :row="scope.row"
            :column="item.prop"
            :index="scope.$index"
            @click="onCellClick"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="visibleHandle"
        fixed="right"
        label="操作"
        align="right"
        class-name="action-column"
        :width="gridEditWidth?gridEditWidth:''"
      >
        <template slot-scope="scope">
          <el-button
            v-for="(item,index) in validateHandles(scope.row)"
            :key="index"
            size="mini"
            :type="item.type?item.type:'text'"
            @click="handleEmit(item.emitName, scope.row)"
          >{{ item.name }}</el-button>
        </template>
      </el-table-column>
      <template slot="append" />
    </el-table>

    <pagination
      v-show="meta.totalCount>0"
      v-if="!hidePagination"
      :total="meta.totalCount"
      :limit="meta.perPage"
      :page.sync="listQuery.page"
      @currentPage="meta.currentPage"
      @pageSize="meta.perPage"
      @pagination="getData"
    />
  </div>
</template>

<script>
import Cell from '@/components/Gridview/components/expand'
import FormatterComponent from '@/components/FormatterView'
import Pagination from '@/components/Pagination'
export default {
  name: 'Gridview',
  components: {
    Cell,
    FormatterComponent,
    Pagination
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    // 表单标题，例如用户、角色
    formTitle: {
      type: String,
      default: ''
    },
    // 表单配置
    formConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表单的model数据
    formData: {
      type: Object,
      default() {
        return {}
      }
    },
    // 表格配置
    gridConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表单标题，例如用户、角色
    gridRef: {
      type: String,
      default: ''
    },
    // 表格配置
    filterConfig: {
      type: Array,
      default() {
        return []
      }
    },
    // 表格按钮配置
    gridHandles: {
      type: Array,
      default() {
        return []
      }
    },
    // 表格死数据
    gridData: {
      type: Array,
      default() {
        return []
      }
    },
    // 数据接口
    apiService: {
      type: [Object, Function],
      default: null
    },
    // 判断是否是异步数据
    isAsync: {
      type: Boolean,
      default: true
    },
    //  表格编辑区域宽度
    gridEditWidth: {
      type: Number,
      default: 0
    },
    //  是否隐藏表格操作
    hideEditArea: {
      type: Boolean,
      default: false
    },
    //  是否隐藏表格操作
    hidePagination: {
      type: Boolean,
      default: false
    },
    // 判断是否是异步数据
    bindParams: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      // 新增修改模态框title
      dialogTitle: '',
      dialogWidth: '',
      // 展示的表格数据，数据来源可能是父组件传递的固定数据，可能是接口请求数据
      showGridData: [],
      meta: {
        // 列表数据总数
        totalCount: 0,
        pageCount: 1,
        // 当前页码
        currentPage: 1,
        // 每页显示数量
        perPage: 20
      },
      listQuery: {
        page: 1
      },
      // 表单数据
      formModel: {},
      //  表格加载状态
      listLoading: false
    }
  },
  computed: {
    visibleHandle() {
      return !this.hideEditArea && this.gridHandles.length > 0
    },
    validateHandles() {
      return row => {
        return this.gridHandles.filter(btn => {
          if (btn.filter) {
            if (typeof btn.filter === 'function') {
              return btn.filter(btn, row) || false
            } else {
              return row[btn.filter] || false
            }
          } else {
            return true
          }
        })
      }
    }
  },
  watch: {
    // 防止表格预置数据不成功，涉及生命周期问题
    gridData() {
      this.showGridData = this.gridData
    },
    // 防止表格预置数据不成功，涉及生命周期问题
    bindParams() {
      this.refresh()
    }
  },
  mounted() {
    this.getData()
  },
  methods: {
    // 获取列表数据
    getData(params = null) {
      this.listLoading = true
      const queryParams = Object.assign(this.listQuery, this.bindParams, params)
      // const params = Object.assign(this.listQuery, this.bindParams)
      if (typeof this.apiService !== 'function') {
        this.apiService.list(queryParams).then(
          response => {
            const { data } = response
            this.showGridData = data.items
            this.meta = data.meta
            this.listLoading = false
          },
          error => {
            console.log(error)
            this.listLoading = false
          }
        )
      } else {
        this.apiService(queryParams).then(
          response => {
            const { data } = response
            this.showGridData = data.items
            this.meta = data.meta
            this.listLoading = false
          },
          error => {
            console.log(error)
            this.listLoading = false
          }
        )
      }
    },
    // 处理相应父组件的事件方法
    onCellClick(row) {
      this.handleEmit('link', row)
    },
    // 处理相应父组件的事件方法
    handleEmit(emitName, row) {
      this.$emit('action', emitName, row)
    },
    handleCurrentChange(page) {
      this.meta.currentPage = page
      this.getData()
    },
    handleSizeChange(size) {
      this.meta.perPage = size
      this.getData()
    },
    // 刷新数据
    refresh() {
      this.getData()
    },
    // Filter数据检索提交
    filterSearch(data) {
      this.listQuery.page = 1
      this.getData()
    },
    // 模态框数据提交
    dialogSubmit(data) {
      this.apiService[data.userId ? 'update' : 'create'](data).then(res => {
        this.getData()
        this.$message.success(this.dialogTitle + '成功！')
      })
    },
    remove(data) {
      //  处理删除逻辑
      this.apiService.delete(data.id).then(res => {
        this.getData()
        this.$message.success('删除成功！')
      })
    },
    view(data) {
      // 处理查看详情逻辑
      this.$router.push({
        path: 'view/' + data.id
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/components/Gridview/components/grid.scss';
</style>
